import { Column, Entity, JoinColumn, JoinTable, ManyToMany, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { UserEntity } from "../../user/entities/user.entity"
import { CategoryEntity } from "../../category/entities/category.entity"
import { Exclude } from "class-transformer";
import { TagEntity } from "src/tag/entities/tag.entity";
import { PostInfoDto } from "../dto/create-post.dot";

@Entity('post')
export class PostsEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({length: 100})
  title: string;

  @ManyToOne((type) => UserEntity, (user) => user.nickname)
  author: UserEntity;

  @Column({type: 'mediumtext', default: null})
  content: string;

  @Column({type: 'mediumtext', default: null, name: 'content_html'})
  contentHtml: string;

  @Column({type: 'text', default: null})
  summary: string;  // 摘要

  @Column({default: ''})
  cover_url: string;

  @Column({type: 'int', default: 0})
  count: number; // 阅读量

  @Column({type: 'int', default: 0, name: 'like_count'})
  like_count: number; // 点赞数

  @Column({type: 'tinyint', default: 0, name: 'is_recommend'})
  is_recommend: number;  // 是否显示推荐

  @Column({type: 'simple-enum', enum: ['draft', 'publish'], default: 'draft'})
  status: string; // 文章状态

  @Exclude()
  @ManyToOne(() => CategoryEntity, (category) => category.posts)
  @JoinColumn({ name: 'category_id' })
  category: CategoryEntity;

  @ManyToMany(() => TagEntity, (tag) => tag.posts)
  @JoinTable({
    name: 'post_tag',
    joinColumns: [{ name: 'post_id'}],
    inverseJoinColumns: [{ name: 'tag_id'}]
  })
  tags: Array<TagEntity>

  @Column({type: 'timestamp', default: null, name: 'publish_time'})
  publish_time: Date;

  @Column('tinyint')
  type:number

  @Column({type: 'timestamp', default: () => "CURRENT_TIMESTAMP"})
  create_time: Date

  @Column({type: 'timestamp', default: () => "CURRENT_TIMESTAMP"})
  update_time: Date

  toResponseObject(): PostInfoDto {
    let responseObj: PostInfoDto = {
      ...this,
      is_recommend: this.is_recommend ? true : false,
    };
    if (this.category) {
      responseObj.category = this.category.name;
    }
    if (this.tags && this.tags.length) {
      responseObj.tags = this.tags.map((item) => item.name);
    }
    if (this.author && this.author.id) {
      responseObj.userId = this.author.id;
      responseObj.author = this.author.nickname || this.author.username;
    }
    return responseObj;
  }
}